package com.example.ymm.modules1.service.dkn;

import cn.afterturn.easypoi.cache.manager.IFileLoader;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.dkn.DknForecastProduct;
import com.example.ymm.modules1.entity.hl.dkn.DknForecastSave;
import com.example.ymm.modules1.entity.hl.dkn.DknProductMapping;
import com.example.ymm.modules1.entity.hl.dkn.DknPurchaseOrder;
import com.example.ymm.modules1.entity.ms.VckStock;
import com.example.ymm.modules1.query.hl.DklForecastQueryCriteria;
import com.example.ymm.modules1.query.hl.DknForecastProductQueryCriteria;
import com.example.ymm.modules1.query.hl.DknProductMappingQueryCriteria;
import com.example.ymm.modules1.query.hl.DknPurchaseOrderQueryCriteria;
import com.example.ymm.modules1.service.dto.dkn.DknEditOrderDto;
import com.example.ymm.modules1.service.dto.dkn.DknForecastStockDto;
import com.example.ymm.modules1.service.dto.dkn.DknNotInOrderDto;
import com.example.ymm.modules1.service.dto.heng.DknCreatePurchaseOrderGroupDto;
import com.example.ymm.modules1.service.dto.heng.DknProductMappingDto;
import com.example.ymm.modules1.service.dto.ms.MsOrderListQueryCriteria;
import com.example.ymm.modules1.service.hl.*;
import com.example.ymm.modules1.service.ms.TProviderPartnerService;
import com.example.ymm.util.*;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * 迪卡侬业务类
 */
@Slf4j
@Service
public class DknForecastService {

    @Value("${forecast.domain}")
    private String domain;
    @Value("${forecast.supplier_code}")
    String supplier_code;

    @Value("${forecast.vendor_plant_code}")
    String vendor_plant_code;

    @Autowired
    private RedisUtil redisUtil;

    List<DknForecastProduct> forecastProducts;


    @Autowired
    DknForecastAccessTokenService dknForecastAccessTokenService;


    @Autowired
    DknForecastProductService dknForecastProductService;
    @Autowired
    private DknForecastCacheService dknForecastCacheService;
    @Autowired
    private DknForecastSaveService dknForecastSaveService;

    @PostConstruct
    public void initFn(){
        Thread thread = new Thread(()->{
            forecastProducts=dknForecastProductService.queryAll(null);
        });
        thread.start();
    }


    /**
     * 查询采购需求
     * @param
     * @return
     */
    public JsonNode getForecast(DklForecastQueryCriteria criteria,YmPageDto ymPage){
        String url=domain+"/cn_api_service/api/v1/data_exchange/forecast";
        JSONObject param=new JSONObject();
        param.put("supplier_code",supplier_code);
        param.put("vendor_plant_code",vendor_plant_code);
        param.put("data_type_code",criteria.getDataTypeCode());
        param.put("nature_view_code",1);
        param.put("pageIndex",ymPage.getPage()-1);
        param.put("pageSize",ymPage.getPageSize());
        return dknForecastAccessTokenService.getJson(url,param);
    }


    /**
     * 提交计划
     * @param
     * @return
     */
    public JsonNode postJsonPlan(JSONArray param){
        String url=domain+"/cn_api_service/api/v1/data_exchange/production_planning";
        return dknForecastAccessTokenService.postJson(url,param);
    }


    public JSONObject forecastTableList(DklForecastQueryCriteria criteria,YmPageDto ymPage){
        String json_str=null;

        JsonNode forecast = getForecast(criteria, ymPage);

        json_str=forecast.toString();

//        ClassPathResource resource = new ClassPathResource("testMapping.json");
//        InputStream formInfoInputStream = null;
//
//        try {
//            formInfoInputStream = resource.getInputStream();
//            json_str = StreamUtils.copyToString(formInfoInputStream, StandardCharsets.UTF_8);
//            formInfoInputStream.close();
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        JSONObject json = JSONObject.parseObject(json_str);
        if(json.getInteger("code") != 200){
            throw new YmException(json.getString("message"));
        }



        return json;
    }





    public void operatorListData(JSONArray result,DklForecastQueryCriteria criteria){

        /**
         * 2段 进阶要求
         */
        //forecastPlanSet(result,criteria);

        //json.getJSONObject("data").put("content",result);
    }

    /**
     * 设置未入库 备货订单，库存
     */
    public JSONArray forecastPlanSet(JSONArray list,DklForecastQueryCriteria criteria,String week){
        String[] split = week.split("-W");

        List<Date> startAndEndOfWeek1 = DateKit.getStartAndEndOfWeek(Integer.parseInt(split[0]), Integer.parseInt(split[1]));

        /**
         * 数据处理
         */
        JSONArray result=new JSONArray();
        for(int i=0; i<list.size(); i++){
            JSONObject obj = list.getJSONObject(i);
            JSONArray itemVOs = obj.getJSONArray("forecastItemVOs");
            JSONObject keyFigureTotal=new JSONObject();
            String itemCode=null;
            String itemName=null;
            String schemaType=null;
            String modelCode=obj.getString("modelCode");

            for(int j=0; j<itemVOs.size(); j++){
                JSONObject itemVO = itemVOs.getJSONObject(j);
                itemCode= itemVO.getString("itemCode");
                String supplySchema=itemVO.getString("supplySchema");

                for (DknForecastProduct forecastProduct :  forecastProducts){
                    if(forecastProduct.getItemCode().equals(itemCode)){
                        itemName=forecastProduct.getItemName();
                        schemaType=forecastProduct.getDataSchema();
                        break;
                    }
                }
                //过滤MTO
                if(UtilValidate.isNotEmpty(criteria.getDataSchema())){
                    String filterSchema=null;//真正要过滤的只有 MTS D，MTO
                    if(criteria.getDataSchema().equals("MTS Hengli")||criteria.getDataSchema().equals("MTO")){
                        filterSchema="MTO";
                    }else{
                        //MTS D
                        filterSchema="MTS D";
                    }
                    if(!supplySchema.equals(filterSchema)){
                        itemVOs.remove(j);
                        j=0;
                        continue;
                    }

                }

                /**
                 * 过滤完之后进行计算
                 */
                JSONObject keyFigure = itemVO.getJSONObject("keyFigure");
                for (String key : keyFigure.keySet()) {
                    //if(!key.contains(" Stock")){

                    if(key.equals("Projected Stock")||key.equals("Supplier Planned WO (EPD)")){
                        continue;//过滤 部分 Stock
                    }
                    if(keyFigureTotal.containsKey(key)){
                        JSONObject keyItem = keyFigureTotal.getJSONObject(key);
                        JSONObject keyItem_old= keyFigure.getJSONObject(key);
//                        if("8602735".equals(modelCode)){
//                        //    System.out.println("--keyItem:"+keyItem);
//                        }
                        for (String k2 : keyItem_old.keySet()) {
                            if(k2.contains("-W")||k2.equals("initialQuantity")){
                                BigDecimal itemTotal = BigDecimal.ZERO;
                                if(UtilValidate.isNotEmpty(keyItem.getBigDecimal(k2))){
                                    itemTotal=itemTotal.add(keyItem.getBigDecimal(k2));
                                }

                                if(UtilValidate.isNotEmpty(keyItem_old.getBigDecimal(k2))){
                                    itemTotal=itemTotal.add(keyItem_old.getBigDecimal(k2));
                                }
                                keyItem.put(k2,itemTotal);
                            }
                        }
                    }else{
                        keyFigure.getJSONObject(key).put("itemCode",itemCode);
//                            keyFigure.getJSONObject(key).put("itemName",itemName);
                        keyFigureTotal.put(key,keyFigure.getJSONObject(key));
                    }
                    // }
                }

            }

            obj.put("itemCode",itemCode);
            obj.put("itemName",itemName);
            obj.put("schemaType",schemaType);

            /**
             * 组装 items
             *
             */
            List<JSONObject> items=new ArrayList<>();
            List<JSONObject> sortArr=new ArrayList<>();
            JSONObject totalJson=new JSONObject();
            BigDecimal initialQuantity = BigDecimal.ZERO;

            for (String key : keyFigureTotal.keySet()) {
                JSONObject key_obj = keyFigureTotal.getJSONObject(key);
                key_obj.put("modelCode",key);

                for (String k2 :key_obj.keySet()) {
                    if(key.equals("Planned DO (EHD)")||key.equals("Firmed DO (EHD)")||key.equals("Validated DO (EHD)")){
                        if(k2.contains("-W")){
                            BigDecimal itemTotal = null;
                            if(totalJson.containsKey(k2)){
                                BigDecimal total = BigDecimal.ZERO;
                                if(UtilValidate.isNotEmpty(key_obj.getBigDecimal(k2))){
                                    total = key_obj.getBigDecimal(k2);
                                }
                                if(UtilValidate.isNotEmpty(totalJson.getBigDecimal(k2))){
                                    itemTotal = total.add(totalJson.getBigDecimal(k2));
                                }
                            }else{
                                itemTotal = key_obj.getBigDecimal(k2);
                            }
                            totalJson.put(k2,itemTotal);
//                        if("8539878".equals(modelCode)&&"2025-W51".equals(k2)){
//                            System.out.println("--旧："+key_obj.getBigDecimal(k2));
//                            System.out.println("--新："+totalJson.getBigDecimal(k2));
//                        }

                        }
                    }
//                    if(key.equals("Planned DO (EHD)")||key.equals("Firmed DO (EHD)")||key.equals("Validated DO (EHD)")){
//                        if(k2.contains("2025-W48")){
//                            System.out.println("--modelCode:"+modelCode+";key:"+key+totalJson.getBigDecimal(k2)+";k2:"+k2);
//                        }
//                    }
                    if(!key.contains(" Stock")){
                        if("initialQuantity".equals(k2)&&UtilValidate.isNotEmpty(key_obj.getBigDecimal(k2))){
                            initialQuantity=initialQuantity.add(key_obj.getBigDecimal(k2));
                        }
                    }
                }
                key_obj.put("itemName",itemName);
                items.add(key_obj);
            }
            /**
             * 合并 汇总对象
             */
            for (String k2 :totalJson.keySet()) {
                obj.put(k2,totalJson.getBigDecimal(k2));
            }
            obj.put("initialQuantity",initialQuantity);//不汇总 stock
            obj.put("children",items);
            if(UtilValidate.isNotEmpty(items)){

                /**
                 *
                 * 过滤hengli
                 *
                 */
                if(UtilValidate.isNotEmpty(criteria.getDataSchema())){
                    if(criteria.getDataSchema().equals(schemaType)){
                        result.add(obj);
                    }
                }else{
                    result.add(obj);
                }
//                result.add(obj);

            }
        }

        List<String> itemCodes=new ArrayList<>();
        List<String> modelCodes=new ArrayList<>();
        for(int i=0; i<result.size(); i++) {
            JSONObject obj = result.getJSONObject(i);
            String modelCode = obj.getString("modelCode");
            String itemCode = obj.getJSONArray("children").getJSONObject(0).getString("itemCode");
            itemCodes.add(itemCode);
            modelCodes.add(modelCode);
        }
        //1 合并库存数量
        DknForecastProductQueryCriteria c=new DknForecastProductQueryCriteria();
        c.setItemCodeIn(itemCodes);
        long start1 = System.nanoTime();
       // System.out.println("--任务1开始");
        String cache_key="cache_order_"+criteria.getDataTypeCode();
//        String cache_key2="cache_stock_"+criteria.getDataTypeCode();
        String v = redisUtil.getString(cache_key);
        List<DknNotInOrderDto> notInOrders=null;
        notInOrders = dknForecastProductService.getNotInOrders(c);
//        if(UtilValidate.isEmpty(v)){
//            notInOrders = dknForecastProductService.getNotInOrders(c);
//            boolean b = redisUtil.setIfAbsent(cache_key, JSONObject.toJSONString(notInOrders), 10, TimeUnit.MINUTES);
//        }else{
//            notInOrders = JSONArray.parseArray(v, DknNotInOrderDto.class);
//        }

        long end1 = System.nanoTime();
        double l1= (end1 - start1) / 1_000_000_000.0;
        System.out.printf("任务1耗时：%.3f 秒%n", l1);
        long start2 = System.nanoTime();


        List<DknForecastStockDto> forecastStock = dknForecastProductService.getForecastStock(c);

        String s = DateKit.dateFormat(startAndEndOfWeek1.get(0), "yyyy-MM-dd");
        c.setStartDate(s);
        List<DknForecastStockDto> outs = dknForecastProductService.outbillList(c);
        long end2 = System.nanoTime();
        double l2= (end2 - start2) / 1_000_000_000.0;
        System.out.printf("任务2耗时：%.3f 秒%n", l2);

        String cache_save_key="cache_save_"+criteria.getDataTypeCode();
        String v3 = redisUtil.getString(cache_save_key);
        List<DknForecastSave> forecastSaves =dknForecastSaveService.getInModelCode(modelCodes);;
//        if(UtilValidate.isEmpty(v)){
//            forecastSaves =dknForecastSaveService.getInModelCode(modelCodes);
//            boolean b = redisUtil.setIfAbsent(cache_save_key, JSONObject.toJSONString(forecastSaves), 10, TimeUnit.MINUTES);
//
//        }else{
//            forecastSaves= JSONArray.parseArray(v3,DknForecastSave.class);
//        }


        //2 设置库存，和备货订单数量
        //3 设置保存数据
        for(int i=0; i<list.size(); i++) {
            JSONObject obj = list.getJSONObject(i);
            String modelCode = obj.getString("modelCode");
            JSONArray old_childrens = obj.getJSONArray("children");
            JSONArray childrens = new JSONArray();//obj.getJSONArray("children")

            JSONArray ls_arr=new JSONArray();
            for(int j=0; j<old_childrens.size(); j++) {
                JSONObject json1 = old_childrens.getJSONObject(j);
                String i_modelCode = json1.getString("modelCode");
                if(i_modelCode.equals("Maximum Stock")||i_modelCode.equals("Minimum Stock")) {
                    ls_arr.add(json1);
                }else{
                    childrens.add(json1);
                }
            }
            DknForecastStockDto dto=null;

            for(DknForecastStockDto dto1: forecastStock){
                if(dto1.getItemCode().equals(obj.getString("itemCode"))){
//                    obj.put("current_stock",UtilValidate.isNotEmpty(dto1.getStockQuantity())?dto1.getStockQuantity().doubleValue():0);
//                    obj.put("initialQuantity",);

                    dto=dto1;
                    break;
                }
            }
            DknForecastStockDto out_dto=null;
            for(DknForecastStockDto dto1: outs){
                if(dto1.getItemCode().equals(obj.getString("itemCode"))){

                    out_dto=dto1;
                    break;
                }
            }

            if(UtilValidate.isNotEmpty(dto)){

                //已出库数量
                JSONObject obj1=new JSONObject();
                obj1.put("modelCode","QTY Shipped Out");
                obj1.put("itemCode",obj.getString("itemCode"));
                obj1.put("itemName",obj.getString("itemName"));
                if(UtilValidate.isNotEmpty(out_dto)){
                    //本周出货
                    obj1.put(week,out_dto.getStockQuantity());
                }
                childrens.add(obj1);

                double initialQuantity = dto.getStockQuantity().add(obj.getBigDecimal("initialQuantity")).doubleValue();
                //当前库存
                JSONObject obj2=new JSONObject();
                obj2.put("initialQuantity",dto.getStockQuantity());
                obj2.put("modelCode","Current Stock");
                obj2.put("itemCode",obj.getString("itemCode"));
                obj2.put("itemName",obj.getString("itemName"));
                childrens.add(obj2);
                obj.put("initialQuantity",initialQuantity);
                //未入库的备货订单数量
                JSONObject obj3=new JSONObject();
                obj3.put("modelCode","Un-Finished Planned DO (EPD)");
                obj3.put("itemCode",obj.getString("itemCode"));
                obj3.put("itemName",obj.getString("itemName"));
                for (String k2 :obj.keySet()) {
                    if (k2.contains("-W")) {
                        String[] weeks = k2.split("-W");//周别
                        List<Date> startAndEndOfWeek = DateKit.getStartAndEndOfWeek(Integer.parseInt(weeks[0]), Integer.parseInt(weeks[1]));
                        List<DknNotInOrderDto> weekNotInOrders = getWeekNotInOrders(startAndEndOfWeek, notInOrders,modelCode);
//                        if(modelCode.equals("8539878")&&k2.equals("2025-W43")){
//                            System.out.println(modelCode);
//                        }
                        BigDecimal bigDecimal = countWeekOrders(weekNotInOrders);
//                        if(weeks[1].equals("4")&&modelCode.equals("8539879")){
//
//                            System.out.println(modelCode);
//                        }
                        obj3.put(k2,bigDecimal);
                    }
                }
                childrens.add(obj3);

                DknForecastSave  unFinishedSave= dknForecastSaveService.findModelCodeAndItemName(modelCode,"Updated Un-Finished Planned DO", forecastSaves);

                //调整备货订单计划
                JSONObject obj6=new JSONObject();
                obj6.put("modelCode","Updated Un-Finished Planned DO");
                obj6.put("itemCode",obj.getString("itemCode"));
                obj6.put("itemName",obj.getString("itemName"));
                //合并保存数据
                if(UtilValidate.isNotEmpty(unFinishedSave)){
                    String txtJson = unFinishedSave.getTxtJson();
                    JSONObject obj_f=JSONObject.parseObject(txtJson);
                    Set<String> f_keys = obj_f.keySet();
                    for(String key:f_keys){
                        if(key.contains("-W")&&UtilValidate.isNotEmpty(obj_f.get(key))){
                            obj6.put(key,obj_f.getBigDecimal(key));
                        }
                    }
                }
                childrens.add(obj6);

                DknForecastSave  newPlannedSave= dknForecastSaveService.findModelCodeAndItemName(modelCode,"New Planned DO (EPD)", forecastSaves);

                // New Planned DO (EPD)
                // 新增备货订单计划
                JSONObject obj5=new JSONObject();
                obj5.put("modelCode","New Planned DO (EPD)");
                obj5.put("itemCode",obj.getString("itemCode"));
                obj5.put("itemName",obj.getString("itemName"));
                //合并保存数据
                if(UtilValidate.isNotEmpty(newPlannedSave)){
                    String txtJson = newPlannedSave.getTxtJson();
                    JSONObject obj_f=JSONObject.parseObject(txtJson);
                    Set<String> f_keys = obj_f.keySet();
                    for(String key:f_keys){
                        if(key.contains("-W")&&UtilValidate.isNotEmpty(obj_f.get(key))){
                            obj5.put(key,obj_f.getBigDecimal(key));
                        }
                    }
                }

                childrens.add(obj5);



                //Project Stock
                //理论库存
                JSONObject obj4=new JSONObject();
                obj4.put("modelCode","Project Stock");
                obj4.put("itemCode",obj.getString("itemCode"));
                obj4.put("itemName",obj.getString("itemName"));

                /**
                 * MTO 的一些物料
                 */
               String mto_arr="2835332，4124777，4528458，4850039";
               if(mto_arr.contains(dto.getItemCode())&&UtilValidate.isNotEmpty(ls_arr)){
                   for(int j=0; j<ls_arr.size(); j++) {
                       JSONObject json1 = ls_arr.getJSONObject(j);
                       String i_modelCode = json1.getString("modelCode");
                       if(i_modelCode.equals("Maximum Stock")) {
                          // ls_arr.add(json1);
                           obj4.put("Maximum Stock",json1);
                       }
                       if(i_modelCode.equals("Minimum Stock")) {
                           obj4.put("Minimum Stock",json1);
                       }
                   }
               }
                childrens.add(obj4);
            }
            childrens.addAll(ls_arr);


            /**
             * 合计total
             */
            for(int j=0; j<childrens.size(); j++) {
                JSONObject child_item = childrens.getJSONObject(j);
                String c_modelCode = child_item.getString("modelCode");
                if("Planned DO (EHD)".equals(c_modelCode)||"Firmed DO (EHD)".equals(c_modelCode)||"Validated DO (EHD)".equals(c_modelCode)) {
                    BigDecimal total=BigDecimal.ZERO;
                    Set<String> keySet = child_item.keySet();
                    for(String key:keySet){
                        if(key.contains("-W")&&UtilValidate.isNotEmpty(child_item.get(key))){
                            total=total.add(child_item.getBigDecimal(key));
                        }
                    }
                    child_item.put("item_total",total);
                }

            }
            obj.put("children",childrens);
//            for(int i2=0; i2<childrens.size(); i2++) {
//                JSONObject child_item = childrens.getJSONObject(i2);
//            }
        }

        return result;
    }


    /**
     * 匹配 哪些未入库订单在这周
     * @param startAndEndOfWeek
     * @param notInOrders
     * @return
     */
    public List<DknNotInOrderDto> getWeekNotInOrders(List<Date> startAndEndOfWeek,List<DknNotInOrderDto> notInOrders,String modelCode){
        List<DknNotInOrderDto> result=new ArrayList<>();
        for(DknNotInOrderDto orderDto: notInOrders){
            if(orderDto.getModelCode().equals(modelCode)){
                /**
                 * 返回 负数：当前日期在另一个日期之前
                 * 返回 0：两个日期相等
                 * 返回 正数：当前日期在另一个日期之后
                 */
                int con1 = orderDto.getJiaoHuoDate().compareTo(startAndEndOfWeek.get(0));
                int con2 = orderDto.getJiaoHuoDate().compareTo(startAndEndOfWeek.get(1));
                if( con1>=0&&con2<=0){
                    result.add(orderDto);
                }
            }

        }
        return result;
    }


    public BigDecimal countWeekOrders(List<DknNotInOrderDto> result){
        BigDecimal total=new BigDecimal(0);
        for(DknNotInOrderDto orderDto: result){
            total=total.add(orderDto.getShengYuNum());
        }
        return total;
    }


    /**
     * 生成订单导出模板
     * @param jsonObject
     * @return
     */
    public List<JSONObject> yiTiaoZhengList(JSONObject jsonObject){
        List<JSONObject> list=new ArrayList<>();
        List<String> itemCodes=new ArrayList<>();
        Map<String,String> map=new HashMap<>();
        List<JSONObject> datalist=new ArrayList<>();
        jsonObject.keySet().forEach(key->{
            if(!key.contains("page")){
                String[] split = key.split(":");
                String itemCode=split[0];
                map.put(itemCode,split[1]);
                JSONObject json1 = jsonObject.getJSONObject(key);
                json1.put("itemCode",itemCode);
                datalist.add(json1);
            }
        });
        map.keySet().forEach(key->{
            itemCodes.add(key);
        });
        if(UtilValidate.isEmpty(itemCodes)){
            return list;
        }
        Date date = new Date();
        String s = DateKit.dateFormat(date, "yyyyMM");

        DknForecastProductQueryCriteria c1=new DknForecastProductQueryCriteria();
        c1.setItemCodeIn(itemCodes);
        List<DknForecastProduct> products = dknForecastProductService.queryAll(c1);
        for(JSONObject jsonObject1: datalist){
            String itemCode=jsonObject1.getString("itemCode");
            DknForecastProduct product = getJsonByItemCode(itemCode, products);
            JSONObject obj=new JSONObject();

            //固定字段 备货订单	国外销售	GW.204	GW.204	人民币
            obj.put("orderType","备货订单");
            obj.put("guoWai","国外销售");
            obj.put("customerNo","GW.204");
            obj.put("customerName","GW.204");
            obj.put("currencyType","人民币");
            obj.put("modelCode",product.getModelCode());
            obj.put("itemCode",product.getItemCode());
            obj.put("xiaoSouNum",jsonObject1.getBigDecimal("value"));//销售数量
            //交货日期
            String weekName = jsonObject1.getString("field");
            String[] split = weekName.split("-W");
            List<Date> startAndEndOfWeek = DateKit.getStartAndEndOfWeek(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
            String monday = DateKit.dateFormat(startAndEndOfWeek.get(0),"yyyy-MM-dd");
            obj.put("jiaoHuoDate",monday);
            //单价
            obj.put("unitPrice",product.getUnitPrice());
            //税率
            obj.put("suiLv","0%");
            //合同号
//            CreateOrderNo orderNo = new CreateOrderNo();
//            String s = orderNo.makeOrderNum("H");
            redisUtil.increment("autoInsert", 1l);
            String no="H-"+s+"000"+redisUtil.get("autoInsert");
            obj.put("hetongNo",no);
            obj.put("chukouGuoJia","备货库存");
            obj.put("waiXianNum",product.getWaiXianNum());//外箱数量
            list.add(obj);
        }

        return list;
    }


    /**
     * 提交计划
     * @param jsonArray
     */
    public void submitPlanData(JSONArray jsonArray){

        JSONArray arr=new JSONArray();
        for(int i=0;i<jsonArray.size();i++){
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            String itemCode=jsonObject.getString("itemCode");
            JSONArray children = jsonObject.getJSONArray("children");

           // if("2835332".equals(itemCode)){
                JSONObject finished=new JSONObject();
                //查找数据
                for(int j=0;j<children.size();j++){
                    JSONObject children_item = children.getJSONObject(j);
                    String modelCode=children_item.getString("modelCode");
                    if("Un-Finished Planned DO (EPD)".equals(modelCode)){
                        finished=children_item;
                        break;
                    }
                }
                //组装数据
                JSONObject json=new JSONObject();
                json.put("itemCode",jsonObject.getString("itemCode"));
                json.put("vendorPlantCode",jsonObject.getString("vendorPlantCode"));
                JSONObject keyFigureObj=new JSONObject();
                JSONObject SupplierPlannedWObyEPD=new JSONObject();

                if(UtilValidate.isNotEmpty(finished)){
                    for(String key:finished.keySet()){
                        if(key.contains("-W")&&UtilValidate.isNotEmpty(finished.getBigDecimal(key))){
                            if(finished.getBigDecimal(key).compareTo(BigDecimal.ZERO)>0){
                                SupplierPlannedWObyEPD.put(key,finished.getBigDecimal(key));
                            }
                        }
                    }
                    keyFigureObj.put("SupplierPlannedWObyEPD",SupplierPlannedWObyEPD);
                }
                json.put("keyFigure",keyFigureObj);
                arr.add(json);

          //  }
        }
        System.out.println("---arr::"+arr);
        JsonNode jsonNode = postJsonPlan(arr);
        String json_str=jsonNode.toString();
        JSONObject json = JSONObject.parseObject(json_str);
        System.out.println(json);
        if(json.getInteger("code") != 200){
            throw new YmException(json.getString("message"));
        }
        System.out.println(json_str);
    }


    public DknForecastProduct getJsonByItemCode(String itemCode,List<DknForecastProduct> products){
        DknForecastProduct product=null;
        for(DknForecastProduct product1:products){
            if(product1.getItemCode().equals(itemCode)){
                product=product1;
            }
        }
        return product;
    }

}
